package com.carbohydrate42.kotlin_compose_demo.config

import android.util.Log
import com.carbohydrate42.kotlin_compose_demo.BuildConfig
import com.carbohydrate42.kotlin_compose_demo.constant.Common
import com.google.gson.GsonBuilder
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object RetrofitConfig {

    private const val BASE_URL = "${BuildConfig.SERVER_URL}/api/"

    private val interceptor = Interceptor { chain ->
        val request = chain.request()

        Log.d(Common.ANDROID_LOG_TAG.label, "请求拦截 ------------- ")
        Log.d(Common.ANDROID_LOG_TAG.label, request.toString())
        Log.d(Common.ANDROID_LOG_TAG.label, "请求拦截 -------------- \n")


        val response = chain.proceed(
            request.newBuilder()
                .url(request.url.newBuilder().build())
                .method(request.method, request.body)
                // todo 加一些公共请求头
                .addHeader("Content-Type", "application/json")
                .addHeader("deviceCode", "A0001")
                .addHeader("token", "token")
                .build()
        )

        Log.d(Common.ANDROID_LOG_TAG.label, "响应拦截 ------------- ")
        Log.d(Common.ANDROID_LOG_TAG.label, response.toString())

        /**
         * 在 interceptor 中获取 okhttp 的响应 json, 参考,
         * https://stackoverflow.com/questions/60671465/retrofit-java-lang-illegalstateexception-closed
         */
        Log.d(
            Common.ANDROID_LOG_TAG.label,
            response.peekBody(Long.MAX_VALUE).string()
        )

        // todo 如果 response.code() > 200 的话, 虽然不会报错, 但是会不解析 json, 在外边调用api后的 body 是 null, 这里只能手动解析一下了
        Log.d(
            Common.ANDROID_LOG_TAG.label,
            response.body.toString()
        )

        // Log.d(
        //     Common.ANDROID_LOG_TAG.label,
        //     Gson()
        //         .fromJson(response.peekBody(Long.MAX_VALUE).string(), HttpResult::class.java)
        //         .toString()
        // )

        Log.d(
            Common.ANDROID_LOG_TAG.label,
            "响应拦截 -------------- \n"
        )

        return@Interceptor response
    }


    val instance: Retrofit by lazy {
        Retrofit.Builder().baseUrl(BASE_URL)
            .addConverterFactory(
                GsonConverterFactory.create(
                    GsonBuilder()
                        .setDateFormat("yyyy-MM-dd HH:mm:ss")
                        .create()
                )
            )
            .client(
                OkHttpClient.Builder().addInterceptor(interceptor)
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .retryOnConnectionFailure(true)
                    .build()
            ).build()
    }
}

